package com.example.exportdatafromweb;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	
	ArrayList<String> directionList;
	ArrayList<String> ingreditionList;
	String sPrepareTime="";
	String sCookTime ="";
	String sRecipename ="";
	String imageURL = "";
	String summary = "";
	
	DataHeper dataHeper;
	
	ArrayList<String> listURL;
	
	String listpath="";
	int curExport =0;
	
	ProgressDialog barProgressDialog;
	Handler updateBarHandler;
	ProgressDialog ringProgressDialog ;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		directionList = new ArrayList<String>();
		ingreditionList = new ArrayList<String>();
		dataHeper = new DataHeper(getApplicationContext());
		final EditText input = (EditText)findViewById(R.id.editTextPath);
		Button btnGetFile = (Button)findViewById(R.id.buttonGetFile);
		Button btnImPort = (Button)findViewById(R.id.buttonImport);
		final TextView textView = (TextView)findViewById(R.id.textViewlistPath);
		btnGetFile.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View paramView) {
				// TODO Auto-generated method stub
				String path = input.getText().toString();
				getFile(path);
				
				textView.setText(listpath);
			}
		});
		
		btnImPort.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View paramView) {
				// TODO Auto-generated method stub
				ringProgressDialog = ProgressDialog.show(MainActivity.this, "Please wait ...", "Importing data ...", true);
				        ringProgressDialog.setCancelable(false);
				        /*new Thread(new Runnable() {
				            @Override
				            public void run() {
				                try {
				                    // Here you should write your time consuming task...
				                    // Let the progress ring for 10 seconds...
				                    Thread.sleep(10000);
				                } catch (Exception e) {
				 
				                }
				                ringProgressDialog.dismiss();
				            }
				        }).start();*/
				if (listURL.size() >0) {
					new doGetTask().execute("");
				}else{
					ringProgressDialog.dismiss();
				}
			}
		});
		
	}
	
	/**
	 * @param filepath
	 */
	private void getFile(String filepath){
		listpath="";
		listURL = new ArrayList<String>();
		try {
			File myFile = new File(Environment.getExternalStorageDirectory().getPath()+"/"+filepath);
			if (myFile.exists()) {
				FileInputStream fIn = new FileInputStream(myFile);
				BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
				String aDataRow = "";
				while ((aDataRow = myReader.readLine()) != null) {
					listURL.add(aDataRow.trim().toString());
					listpath += aDataRow + "\n";
				}
				myReader.close();
			}else{
				listpath = "file not found";
			}
		} catch (Exception e) {
			listpath = "file not found";
			e.printStackTrace();
		}
		
	};
	/**
	 * @author ThangTB
	 *	this task for show image in scroll
	 */
	private class doGetTask extends AsyncTask<Object, Object, Object>{
		FoodEntity entity;
		public doGetTask() {
			// TODO Auto-generated constructor stub
			entity = new FoodEntity();
		}
		/* (non-Javadoc)
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		@Override
		protected Object doInBackground(Object... params) {
			Document doc;
			try {
		 
				// need http protocol
				String urlPath = listURL.get(curExport);
//				doc = Jsoup.connect("http://www.vahrehvah.com/roomali-roti#.UxNIuJDojjs").get();
				doc = Jsoup.connect(urlPath).get();
				// get page title
				String title = doc.title();
				sRecipename = title;
//				figure
				Elements figures = doc.select("figure");
				for (Element figure : figures) {
					Elements imgs = figure.select("img");
					if (!imgs.isEmpty()) {
						if (imgs.get(0).attr("rel").equals("image_src")) {
							imageURL = imgs.get(0).attr("src");
						}
					}
				}
				// get all links
				Elements links = doc.select("div");
				for (Element link : links) {
					if (link.hasClass("iteam-description")) {
						String s = link.ownText();
						summary = s;
//						System.out.println("Description : " + s);
					}
					if (link.hasClass("recipe-table")) {
						Elements tblRecips = link.select("recipe-table");
						for (Element tblRecip : tblRecips) {
							Elements trRecips = tblRecip.select("tr");
							for (Element trRecip : trRecips) {
								ingreditionList.add(trRecip.text());
							}
						}
						String s = link.text();
//						System.out.println("in-- : " + s);
//						System.out.println("HTML-- : " + link.html());
//						link.select("td#");
//						Elements es = link.getElementsByClass("recipe-table");
//						for (Element e : es) {
//							System.out.println("in--- : " +e.text());
//						}
					}
					if (link.hasClass("iteam-info")) {
						Elements infos = link.select("div.span12").select("table.table");
						for (Element info : infos) {
							String prepare = info.text();
							String prepareTime = prepare.substring(prepare.indexOf("Preparation Time")+"Preparation Time".length(), prepare.indexOf("Ingredient"));
							String cookTime = prepare.substring(prepare.indexOf("Cooking Time")+"Cooking Time".length(), prepare.indexOf("Recipe Type"));
							sPrepareTime = prepareTime.trim().toString();
							sCookTime = cookTime.trim().toString();
						}
					}
					if (link.hasClass("directions")) {
						Elements directions = link.select("div.directions-content li");
						for (Element direction : directions) {
							directionList.add(direction.text());
						}
						directionList.add(link.select("div.directions-content").get(0).ownText()); 
					}
		 
				}
		 
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				entity.setRecipe_name(sRecipename);
				entity.setImage(imageURL);
				entity.setPrepare_time(sPrepareTime);
				entity.setCook_time(sCookTime);
				String direction = "";
				for (int i = 0; i < directionList.size(); i++) {
					direction+=directionList.get(i)+"<br>";
				}
				String ingredition="";
				for (int i = 0; i < ingreditionList.size(); i++) {
					if (i != 0) {
						ingredition+=ingreditionList.get(i)+"<br>";
					}
				}
				entity.setIngredient(ingredition);
				entity.setDirections(direction);
				entity.setSummary(summary);
				
			}
			
			return null;
		}
		
		/* (non-Javadoc)
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(Object result) {
			new doDownLoadImage(entity).execute();
			super.onPostExecute(result);
		}
	} 
	

	/**
	 * @author thangtb
	 * @sine Mar 6, 2014
	 */
	private class doDownLoadImage extends AsyncTask<Object, Object, Object>{
		FoodEntity entity;
		String fileName = "";
		public doDownLoadImage(FoodEntity entity) {
			// TODO Auto-generated constructor stub
			this.entity = entity;
		}
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}
		
		@Override
		protected Object doInBackground(Object... params) {
			// TODO Auto-generated method stub
			try {
				fileName = RunAndSaveSdcard("", this.entity);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Object result) {
			// TODO Auto-generated method stub
			Log.d("ThangTB", "download image done");
			this.entity.setImage(fileName);
			boolean a = dataHeper.insertCeleb(this.entity);
			if (a) {
				Log.d("ThangTB", "import done");
			}else{
				Log.d("ThangTB", "import fail");
			}
			curExport ++;
			if (curExport != listURL.size()) {
				new doGetTask().execute("");
			}else{
				ringProgressDialog.dismiss();
				Toast.makeText(getApplicationContext(), "Import Done.", Toast.LENGTH_LONG).show();
			}
			super.onPostExecute(result);
		}
	}
	
	
	/**
	 * @author thangtb
	 * @since Mar 6, 2014 - 8:07:59 PM
	 * @param pathsave
	 * @param foodEntity
	 * @return
	 * @throws IOException
	 */
	public String RunAndSaveSdcard(String pathsave, FoodEntity foodEntity) throws IOException
	{
//		pathsave = Environment.getExternalStorageDirectory().getPath()+"/file";
		pathsave = Environment.getExternalStorageDirectory().getPath()+"/Android/data/"+getPackageName()+"/file";
		Log.d("FileCache", "path " + pathsave);
		try {
    		File f =new File(pathsave);
            if(!f.exists())
            	f.mkdirs();
		} catch (Exception e) {
			Log.d("FileCache", "Error in init FileCache; " + e.getMessage());
			e.printStackTrace();
		}
		
		InputStream ips =null;
		int lengthOfFile;
		int statusCode;
		try {
			URL url1 = new URL( foodEntity.getImage() );
			URLConnection url_connection;// = url1.openConnection();
			url_connection = url1.openConnection();
			url_connection.setConnectTimeout(20000);
			url_connection.setReadTimeout(20000);
			url_connection.setAllowUserInteraction(false);         
			url_connection.setDoOutput(true);

			

			if ( url_connection instanceof HttpURLConnection)
			{
				HttpURLConnection httpConnection = (HttpURLConnection) url_connection;
				httpConnection.connect();
				lengthOfFile = url_connection.getContentLength();
			   statusCode = httpConnection.getResponseCode();
			   // do something with code .....
				if(statusCode == 404 || lengthOfFile == 0){
					 Log.d("ThangTB","##status "+ statusCode +" "+  "image not found");
				}
				else{
					if(statusCode ==-1){
						Log.d("ThangTB","## conect to server has problem --> reconnect  " + foodEntity.getImage() );
						httpConnection.disconnect();
						httpConnection = (HttpURLConnection) url1.openConnection();
						httpConnection.connect();
						lengthOfFile = url_connection.getContentLength();
						   statusCode = httpConnection.getResponseCode();
						   if(statusCode !=-1){
							   ips = new BufferedInputStream(httpConnection.getInputStream(),8192);
						   }
						   else{
							   Log.d("ThangTB","## try :( conect to server has problem --> reconnect  " + foodEntity.getImage() );
						   }
					}
					else{
						ips = new BufferedInputStream(url1.openStream(),8192);
					}
				}
			}
			else
			{
			   System.err.println ("error - not a http request!");
			   ips = new BufferedInputStream(url1.openStream(),8192);
			}

			
		}
		catch(InterruptedIOException e)
		{
			e.printStackTrace();
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		String fileName ="";
		fileName = foodEntity.getRecipe_name()+foodEntity.getImage().substring(foodEntity.getImage().lastIndexOf("."), foodEntity.getImage().length());
		File fileSave = new File(pathsave+"/"+fileName);
		if(ips!=null)
		{
			OutputStream ops;
			try {
				ops = new FileOutputStream(fileSave, false);

				byte[] data = new byte[1024];
				int total = 0;
				int count = 0;
				while ((count = ips.read(data))!= -1)
				{
//					if(isExit)
//						break;
					ops.write(data, 0, count);	
					total+= count;
				}
//				Log.d("ThangTB", "##download end   total = %d of file %s",total,url );
				
				ops.flush();
				ops.close();
				ips.close();
				return fileName;
			}
			catch (Exception e) 
			{
//				fileSave.delete();
				e.printStackTrace();
			}	
			finally {
		        if (ips != null) {
		        	ips.close();
		        } 
		    }
		}
		return "";
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
